#!coding:utf8
import json
import sys
import time
sys.path.append("..")
sys.setdefaultencoding( "utf-8" )
from driver import *

import requests
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()

class XRAPI(object):
    # 获取token
    def GetToken(self):
        url = 'https://app.dtuip.com/oauth/token'
        print url
        params = {
            "grant_type": "password",
            "username": "18358761272",
            "password": "9519513737"
        }
        headers = {
            "authorization": "Basic NWM2NDI0ZjM0ODNkNDFkZWI4MGIyZThkNTJlZDBkYTA6OTNiNTgzNGZlMmJkNDdlNDk5YTQ2YTk3MjA0OGI1Y2Q=",

        }
        res = requests.post(url,data=params,headers=headers)
        return json.loads(res.text)

    # # 获取设备信息
    # def GetMessage(self,accessToken, clientId):
    #     url ="https://app.dtuip.com/api/device/getDeviceGroup"
    #     headers = {
    #         "authorization":"Bearer "+accessToken,
    #         "tlinkAppId": clientId
    #     }
    #     body = {
    #         "userId":"62382"
    #     }
    #     res = requests.get(url=url,headers=headers,data=json.dumps(body))
    #     return json.loads(res.text)

    #     # 分页获取设备 获取大炉 小炉温度
    # def GetMessage_page(self,accessToken, clientId):
    #     url ="https://app.dtuip.com/api/device/getDevices"
    #     headers = {
    #         "authorization":"Bearer "+accessToken,
    #         "tlinkAppId": clientId
    #     }
    #     body = {
    #         "userId":"62382",
    #         "currPage":1
    #     }
    #     res = requests.get(url=url,headers=headers,data=json.dumps(body))
    #     return json.loads(res.text)

    # 分页获取用户传感器
    # 【注意】by robbin，测试发现这个接口就有设备列表和设备下传感器列表以及各个传感器的当前值
    def GetMessage_page1(self,accessToken, clientId):
        url ="https://app.dtuip.com/api/device/getDeviceSensorDatas"
        headers = {
            "authorization":"Bearer "+accessToken,
            "tlinkAppId": clientId
        }
        body = {
            "userId":"62382",
            #【注意】by robbin，虽然本接口返回的JSON结构有分页，但是返回的数据好像是整体而不是数据显示的每页多少行，而且即使这里传入其他页，测试返回也是无数据！
            "currPage":1   
        }
        res = requests.get(url=url,headers=headers,data=json.dumps(body))
        return json.loads(res.text)
    
    # # .根据id查找设备信息
    # def GetMessage_id(self,accessToken, clientId,deviceNo,id):
    #     url ="https://app.dtuip.com/api/device/getSingleDeviceDatas"
    #     headers = {
    #         "authorization":"Bearer "+accessToken,
    #         "tlinkAppId": clientId
    #     }
    #     body = {
    #         "userId":"62382",
    #         "currPage":1,
    #         "deviceId":id,
    #         "deviceNo": deviceNo,
    #     }
    #     res = requests.get(url=url,headers=headers,data=json.dumps(body))
    #     return json.loads(res.text)
    
    # #获取设备数据
    # def GetMessage_msg(self,accessToken, clientId,value):
    #     url ="https://app.dtuip.com/api/device/getSingleSensorDatas"
    #     headers = {
    #         "authorization":"Bearer "+accessToken,
    #         "tlinkAppId": clientId
    #     }
    #     body = {
    #         "userId":"62382",
    #         "sensorId":value
    #     }
    #     res = requests.get(url=url,headers=headers,data=json.dumps(body))
    #     return json.loads(res.text)

class Project(IOTOSDriverI):
    # 1、通信初始化
    def InitComm(self, attrs):
        self.setPauseCollect(False)
        self.setCollectingOneCircle(False)
        self.online(True)
        
        #24小时定时器获取天气信息
        self.heart_beat();

    def heart_beat(self):
        url ="https://devapi.qweather.com/v7/weather/3d?location=101210101&key=71d7f850636a4f21b9625f918a3c543c"
        res = requests.get(url=url)
        self.warn(res.text)
        objtmp = json.loads(res.text);
        if objtmp['daily'] and objtmp['daily'][0] and objtmp['daily'][0]['tempMin']:
            self.info(self.setValue(u'气温', objtmp['daily'][0]['tempMin'] + '~ ' + objtmp['daily'][0]['tempMax'],auto_created=True))
            
        if objtmp['daily'] and objtmp['daily'][0] and objtmp['daily'][0]['humidity']:
            self.info(self.setValue(u'湿度', objtmp['daily'][0]['humidity'],auto_created=True))

        if objtmp['daily'] and objtmp['daily'][0] and objtmp['daily'][0]['pressure']:
            self.info(self.setValue(u'气压', objtmp['daily'][0]['pressure'],auto_created=True))

        #定时器执行24小时循环
        threading.Timer(60 * 60 * 24, self.heart_beat).start()
        
    # #2、采集引擎回调，可也可以开启，也可以直接注释掉（对于主动上报，不存在遍历采集的情况）
    def Collecting(self, dataId):

        #【注意】by robbin用collecting线程循环来循环刷取数据，没必要按照接口流程过期刷token那么复杂流程！
        self.obj = XRAPI()
        self.token = self.obj.GetToken()        
        access_token = self.token["access_token"]
        clientId = self.token["clientId"]
        Message = self.obj.GetMessage_page1(access_token, clientId)
           
        for i in range(len(Message['dataList'])):
            deviceData = Message['dataList'][i]
            for j in range(len(deviceData['sensorsList'])):
                sensorData = deviceData['sensorsList'][j]
                name = sensorData['deviceName'] + '-' + sensorData['sensorName']
                value = float(sensorData['value'])
                
                self.warn(name + "：" + str(value))
                
                def datetime2timestamp(datetime):
                    return int(time.mktime(time.strptime(datetime,"%Y-%m-%d %H:%M:%S")))  
                
                #传入实际查询返回数据，以及返回内容带有值对应的时间
                
                self.warn(sensorData['updateDate']) #2022-11-01 13:20:04
                timestamp = None #417197105 #1641052800 #datetime2timestamp(sensorData['updateDate']) - 10000000;   #1667280004
                self.info(self.setValue(name, value,timestamp = timestamp,auto_created=True))
                            
                #不传入时间，本地自动按照上报这一刻的时间戳！
                #self.info(self.setValue(name, value,auto_created=True))
        return ()


    # 3、控制
    # 广播事件回调，其他操作访问
    def Event_customBroadcast(self, fromUuid, type, data):
        '''*************************************************
        TODO
        **************************************************'''
        return json.dumps({'code': 0, 'msg': '', 'data': ''})

    # 4、查询
    # 查询事件回调，数据点查询访问
    def Event_getData(self, dataId, condition):
        '''*************************************************
        TODO
        **************************************************'''
        return json.dumps({'code': 0, 'msg': '', 'data': ''})

    # 5、控制事件回调，数据点控制访问
    def Event_setData(self, dataId, value):
        '''*************************************************
        TODO
        **************************************************'''
        return json.dumps({'code': 0, 'msg': '', 'data': ''})

    # 6、本地事件回调，数据点操作访问
    def Event_syncPubMsg(self, point, value):
        '''*************************************************
        TODO
        **************************************************'''
        return json.dumps({'code': 0, 'msg': '', 'data': ''})